package com.microboom.web;

import com.microboom.service.exception.PasswordIncorrectException;
import com.microboom.service.exception.RegisterUserException;
import com.microboom.service.exception.UserExistException;
import com.microboom.service.exception.UsernameNotExistException;
import com.microboom.web.exception.RegisterParameterException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * 指定本类，是专门用于处理 UserController 中的各个方法抛出的异常。
 * 如果有需要，它可以处理多个 Controller 类抛出的异常。
 */
@ControllerAdvice(assignableTypes = {UserController.class})
public class UserControllerExceptionHandler {

    /**
     * 本方法专门用于处理，Controller 抛出 UsernameNotExistException 异常。
     */
    @ExceptionHandler(UsernameNotExistException.class)
    public ModelAndView handleUsernameNotExistException(UsernameNotExistException ex) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("login");
        mav.addObject("errorMsg", "用户名不存在");
        return mav;
    }

    /**
     * 本方法专门用于处理，Controller 抛出 PasswordIncorrectException 异常。
     */
    @ExceptionHandler(PasswordIncorrectException.class)
    public ModelAndView handlePasswordIncorrectException(PasswordIncorrectException ex) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("login");
        mav.addObject("errorMsg", "密码不正确");
        return mav;
    }

    @ExceptionHandler(UserExistException.class)
    public ModelAndView handleUserExistException(UserExistException ex) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("reg");
        mav.addObject("regErrorMsg", "用户已存在");
        return mav;
    }

    @ExceptionHandler(RegisterUserException.class)
    public ModelAndView handleRegisterUserException(RegisterUserException ex) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("reg");
        mav.addObject("regErrorMsg", "服务器内部错误，请联系管理员");
        return mav;
    }

    @ExceptionHandler(RegisterParameterException.class)
    public ModelAndView handleRegisterParameterException(RegisterParameterException ex) {
        ModelAndView mav = new ModelAndView();

        List<FieldError> list = ex.getBindingResult().getFieldErrors();

        for (FieldError error : list) {
            if (error.getField().equals("username")) {
                mav.addObject("usernameErrorMsg", error.getDefaultMessage());
            }
            else if (error.getField().equals("password")) {
                mav.addObject("passwordErrorMsg", error.getDefaultMessage());
            }
        }

        mav.setViewName(ex.getViewName());
        return mav;
    }
}
